package snapex.core.security;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
	
	@Value("${snapex.security.enabled}")
	boolean isSecurityEnabled;
	
	@Bean("MyOAuth2RestTemplate")
	@LoadBalanced
	public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
	    return new OAuth2RestTemplate(details, oauth2ClientContext);
	}
	
	@Configuration
	@EnableWebSecurity
	@EnableGlobalMethodSecurity(prePostEnabled = true)
	static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
		@Override
		protected void configure(HttpSecurity http) throws Exception {
			log.info("****Override WebSecurityConfigurerAdapter.configure(HttpSecurity) to DO NOTHING! Use ResourceServerConfigurerAdapter.configure(HttpSecurity)");
		}		
	}
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
		
		log.info("**********ResourceServerConfiguration:configure(HttpSecurity http)**********isSecurityEnabled={}",isSecurityEnabled);
		
		if(isSecurityEnabled){
			log.info("**********authenticate /expense/** request**********");	
			
			http.authorizeRequests()
				.antMatchers("/expense/**").authenticated()				
				.anyRequest().permitAll();							
		}
		else
		{				
			log.info("**********any request anonymous**********");				
			http.authorizeRequests().anyRequest().permitAll();	
		}	
	}	
}
